import _ from 'lodash';
import store from '@/store';
// 角色字典
export const ROLES = {
  ADMIN_SELFT: 'XST000',
  ADMIN: 'XST001',
  TRADER: 'XST002',
  AUDITOR: 'XST003',
  OPERATOR: 'XST005'
};
const ROLES_GROUP = {
  TRADER: ROLES.TRADER,
  AUDITOR: ROLES.AUDITOR,
  OPERATOR: ROLES.OPERATOR
};
// 路由权限字典
const ROUTERS = {
  summary: 'ZCQJ', // 资产全景
  position: 'ZHCC', // 账户持仓
  record: 'JYJL', // 交易记录
  cart: 'GWC', // 购物车
  selfSelected: 'ZXCP', // 自选产品
  subscribe: 'SJFW', // 数据服务
  statement: 'ZDCX', // 账单查询
  dividend: 'FHCX', // 分红查询
  contract: 'DZHT', // 电子合同
  bankTransfer: 'YZZZ', // 银证转账
  permission: 'WDQX', // 我的权限
  audit: 'DDSH', // 订单审核
  permissionManage: 'QXGL', // 权限管理
  notifyQuery: 'FWTX' // 服务提醒
};
// 角色名称
export const ROLE_NAME_CN = {
  OPERATOR: '管理员',
  TRADER: '交易员',
  AUDITOR: '审核员'
};
export const ROLES_NAME = {
  OPERATOR: 'OPERATOR',
  TRADER: 'TRADER',
  AUDITOR: 'AUDITOR'
};
export const TRADER = ROLES_NAME.TRADER;
export const AUDITOR = ROLES_NAME.AUDITOR;
export const OPERATOR = ROLES_NAME.OPERATOR;

// 用户中心，角色优先级 (多个角色时，优先展示哪个角色的视图)
const ACCOUNT_ROLES_ORDER = [
  OPERATOR,
  TRADER,
  AUDITOR
];
// 进入用户中心时，角色对应默认访问的菜单
export const ACCOUNT_DEFAULT_MENU = {
  TRADER: 'record',
  AUDITOR: 'audit',
  OPERATOR: 'permissionManage'
};
// 操作权限字典 - v-permission 从这里取值
const HANDLES = {
  // 角色对应操作
  TRADE: 'trade', // 交易操作（认购，申购，批量购买，撤单，取消，赎回，修改分红方式，预约赎回，提前回购，回访）
  AUDIT: 'audit', // 审核操作
  OPERATE: 'operate', // 管理员操作

  CART: 'cart', // 加购
  SELF_SELECTED: 'selfSelected', // 加自选
  RECORD_EXPORT: 'record.export', // 交易记录页，导出交易记录

  // 表格操作栏可见性 [routerName].operation
  GM_OPERATION: 'publicfundList.operation',
  THB_OPERATION: 'tianhuibaoList.operation',
  SYPZ_OPERATION: 'incomeReceiptsList.operation',
  GDLC_OPERATION: 'seniorList.operation',
  POSITION_OPERATION: 'positionList.operation',

  // 动态权限
  dynamic: {
    // 管理员 - 投资类型
    OPERATOR: {
      GM: 'OPERATOR.GM',
      SYPZ: 'OPERATOR.SYPZ',
      THB: 'OPERATOR.THB',
      GDLC: 'OPERATOR.GDLC'
    }
  }
};

function getRoleNameCnOptions (obj, order) {
  return order.map(role => {
    return {
      value: role,
      label: obj[role]
    };
  });
}
export const ROLE_NAME_CN_OPTIONS = getRoleNameCnOptions(ROLE_NAME_CN, ACCOUNT_ROLES_ORDER);
export const ALL_ROLES = Object.values(ROLES);
export const ALL_ROLES_NAME = Object.values(ROLES_NAME);
export const ALL_ROUTERS = Object.values(ROUTERS);
// 管理员可选路由权限
export const ALL_CUSTOM_ROUTERS = [
  ROUTERS.position, // 账户持仓
  ROUTERS.record, // 交易记录
  ROUTERS.cart, // 购物车
  ROUTERS.subscribe, // 数据服务
  ROUTERS.statement, // 账单查询
  ROUTERS.dividend, // 分红查询
  ROUTERS.contract, // 电子合同
  ROUTERS.bankTransfer, // 银证转账
  ROUTERS.notifyQuery // 服务提醒
];
// 角色默认路由权限
export const ROLE_ROUTERS = {
  TRADER: [
    ROUTERS.summary,
    ROUTERS.position,
    ROUTERS.record,
    ROUTERS.cart,
    ROUTERS.selfSelected,
    ROUTERS.statement,
    ROUTERS.dividend,
    ROUTERS.contract,
    ROUTERS.permission,
    ROUTERS.notify
  ],
  AUDITOR: [
    ROUTERS.permission,
    ROUTERS.audit,
    ROUTERS.notify
  ],
  OPERATOR: [
    ROUTERS.summary,
    ROUTERS.permission,
    ROUTERS.permissionManage
  ]
};
// 角色默认操作权限
export const ROLE_HANDLES = {
  TRADER: [
    HANDLES.TRADE,
    HANDLES.CART,
    HANDLES.SELF_SELECTED,
    HANDLES.GM_OPERATION,
    HANDLES.THB_OPERATION,
    HANDLES.SYPZ_OPERATION,
    HANDLES.GDLC_OPERATION,
    HANDLES.POSITION_OPERATION
  ],
  AUDITOR: [
    HANDLES.AUDIT
  ],
  OPERATOR: [
    HANDLES.OPERATE,
    HANDLES.RECORD_EXPORT
  ]
};

export function isTrader (rolesName) {
  if (typeof rolesName === 'string') {
    rolesName = [rolesName];
  }
  return rolesName.includes(TRADER);
}
export function isAuditor (rolesName) {
  if (typeof rolesName === 'string') {
    rolesName = [rolesName];
  }
  return rolesName.includes(AUDITOR);
}
export function isOperator (rolesName) {
  if (typeof rolesName === 'string') {
    rolesName = [rolesName];
  }
  return rolesName.includes(OPERATOR);
}
export function isAnyRoles (rolesName) {
  if (typeof rolesName === 'string') {
    rolesName = [rolesName];
  }
  return _.intersection(rolesName, ALL_ROLES_NAME).length > 0;
}
/**
 * 检测当前角色是否有某个操作权限，或者没有某个权限
 * @param {array} rolesName - 角色名称组
 * @param {string | array} handle - 操作权限
 * @param {string} type - 判断类型
 * - all：包含全部权限
 * - any：包含任意一个权限
 * - exclude：不包含权限
 * @return {boolean} 布尔值
 */
export function hasPermissionHandle (rolesName, handle, type = 'all', isDynamic) {
  if (typeof rolesName === 'string') {
    rolesName = [rolesName];
  }
  if (typeof handle === 'string') {
    handle = [handle];
  }

  // 动态权限集合
  function combineDynamic (result, roleName) {
    const dynamic = HANDLES.dynamic[roleName];
    let storeFundType = [];
    if (roleName === 'OPERATOR') {
      storeFundType = store.getters.operatorInvestType;
    } else if (roleName === 'TRADER') {
      storeFundType = store.getters.traderFundType;
    } else {
      return result;
    }
    // 循环角色，获取投资类型
    const roleDynamicFundTypeHandle = storeFundType.reduce((r, fundType) => {
      const handle = dynamic[fundType];
      if (handle) {
        r.push(handle);
      }
      return r;
    }, []);
    result.push(...roleDynamicFundTypeHandle);
    return result;
  }

  // 固定权限集合
  function combineStatic (result, roleName) {
    const roleHandle = ROLE_HANDLES[roleName];
    if (roleHandle) {
      result.push(...roleHandle);
    }
    return result;
  }

  const combine = rolesName.reduce(isDynamic ? combineDynamic : combineStatic, []);
  const sameCount = _.intersection(combine, handle).length;
  const flag = {
    all: sameCount === handle.length,
    any: sameCount > 0,
    exclude: sameCount === 0
  };

  return flag[type];
}
/**
 * 通过角色代码获得角色名
 * 'XST000' => 'OPERATOR'
 */
export function getRoleNameByRoleID (role) {
  let result = '';
  Object.entries(ROLES_GROUP).forEach(item => {
    const [roleName, roleIds] = item;
    if (roleIds.includes(role)) {
      result = roleName;
    }
  });
  return result;
}
/**
 * 通过角色代码组获得角色名组
 * ['XST002', 'XST005'] => ['OPERATOR', 'TRADER']
 */
export function getRolesNameByRolesID (roles) {
  const result = roles.reduce((arr, role) => {
    const name = getRoleNameByRoleID(role);
    if (!arr.includes(name) && name) {
      arr.push(name);
    }
    return arr;
  }, []);
  return result;
}
/**
 * 通过角色代码组获得角色名汉字组
 * ['XST002', 'XST005'] => ['管理员', '交易员']
 */
export function getRolesNameCNByRolesID (roles) {
  const rolesName = getRolesNameByRolesID(roles);
  const result = rolesName.map(item => ROLE_NAME_CN[item]);
  return result;
}
/**
 * 通过角色获取进入我的账户时要跳转的路由
 * ['OPERATOR', 'TRADER'] =排序=> 'record'
 */
export function getAccountRouteByRolesName (rolesName) {
  let routeName = '';
  for (let i = 0; i < ACCOUNT_ROLES_ORDER.length; i++) {
    const roleName = ACCOUNT_ROLES_ORDER[i];
    if (rolesName.includes(roleName)) {
      routeName = ACCOUNT_DEFAULT_MENU[roleName];
      break;
    }
  }
  return routeName;
}
/**
 * 通过角色获取默认角色
 * ['OPERATOR', 'TRADER'] =排序=> 'TRADER'
 */
export function getDefaultRoleByRolesName (rolesName) {
  let result = '';
  for (let i = 0; i < ACCOUNT_ROLES_ORDER.length; i++) {
    const roleName = ACCOUNT_ROLES_ORDER[i];
    if (rolesName.includes(roleName)) {
      result = roleName;
      break;
    }
  }
  return result;
}
/**
 * 通过接口返回的菜单权限，返回路由名称
 * ['ZHCC', 'JYJL'] => ['position', 'record']
 */
export function getRoutesNameByRoutesPermission (permissions) {
  const routesName = [];
  Object.entries(ROUTERS).map(([routeName, routePermission]) => {
    permissions.includes(routePermission) && routesName.push(routeName);
  });
  return routesName;
}

/**
 * 通过路由代码，返回路由名称
 * @param {string} routeCodes - 路由代码
 * @param {boolean} isReverse - 反向转换
 * @return {array} - 路由名称数组
 * ['WDQX', 'DDSH', 'FWTX'] => ['permission', 'audit', 'notify']
 * 'WDQX' => 'permission'
 */
export function getRouteNameByRouteCode (arg, isReverse) {
  const isArray = Array.isArray(arg);
  let result = isArray ? [] : '';
  Object.entries(ROUTERS).forEach(([routeName, routeCode]) => {
    if (isReverse) {
      // 路由名称转路由代码
      if (isArray) {
        if (arg.includes(routeName)) {
          result.push(routeCode);
        }
      } else {
        if (arg === routeName) {
          result = routeCode;
        }
      }
    } else {
      // 路由代码转路由名称
      if (isArray) {
        if (arg.includes(routeCode)) {
          result.push(routeName);
        }
      } else {
        if (arg === routeCode) {
          result = routeName;
        }
      }
    }
  });
  return result;
}

/**
 * 通过路由名称和角色路由权限，获取角色名
 * @param {string} routeName - 路由名称
 * @param {object} permissionRouters - 角色路由权限
 * @return {string} - 角色名
 */
export function getRoleNameByPermissionRouters (routeName, permissionRouters) {
  let result = '';
  for (let i = 0; i < ACCOUNT_ROLES_ORDER.length; i++) {
    const roleName = ACCOUNT_ROLES_ORDER[i];
    const routers = permissionRouters[roleName];
    const routeCode = getRouteNameByRouteCode(routeName, 1);
    if (routers.includes(routeCode)) {
      result = roleName;
      break;
    }
  }
  return result;
}

/**
 * 路由是否在左侧菜单里
 * @param {string} routeName - 路由名称
 * @returns {boolean}
 */
export function isRouteNameInMenuRoute (routeName) {
  const routeCode = getRouteNameByRouteCode(routeName, 1);
  return Object.values(ROUTERS).includes(routeCode);
}